import { Component, Host, h, forceUpdate, Method, ComponentInterface, State } from '@stencil/core';
import { notNilEmpty } from 'qx-util';
import { DrawerItem } from '../../interface';

/**
 * 顶级飘窗导航
 *
 * @author chitanda
 * @date 2021-05-31 17:05:18
 * @export
 * @class IBzDrawerExp
 */
@Component({
  tag: 'ibz-drawer-exp',
  styleUrl: 'ibz-drawer-exp.scss',
  shadow: true,
})
export class IBzDrawerExp implements ComponentInterface {
  ref: HTMLDivElement;

  @State()
  overlayIndex: number = 500;

  @State()
  hidden: boolean = false;

  @State()
  items: DrawerItem[] = [];

  @Method()
  async setItems(items: DrawerItem[]): Promise<void> {
    if (items) {
      this.items = items;
      forceUpdate(this);
    }
  }

  /**
   * 显示或隐藏项
   *
   * @author chitanda
   * @date 2021-06-02 17:06:20
   * @param {MouseEvent} e
   * @param {DrawerItem} item
   */
  showChange(e: MouseEvent, item: DrawerItem): void {
    const ref = item.ref;
    const bol = ref.getAttribute('hidden');
    const x = e.pageX - window.scrollX;
    const y = e.pageY - window.scrollY;
    if (bol == 'true') {
      this.items.forEach(self => {
        if (self.id !== item.id) {
          self.ref.hide(x, y);
        }
      });
      ref.show(x, y);
      this.overlayIndex = ref.overlayIndex;
    } else {
      ref.hide(x, y);
    }
    forceUpdate(this);
  }

  componentDidUpdate(): void {
    const items = this.ref?.children;
    if (notNilEmpty(items)) {
      for (let i = 0; i < items.length; i++) {
        const item = this.items[i];
        const dom = items.item(i) as HTMLElement;
        const offsetParent = dom.offsetParent as HTMLElement;
        if (offsetParent) {
          const x = dom.offsetWidth / 2 + offsetParent.offsetLeft + dom.offsetWidth * i;
          const y = dom.offsetHeight / 2 + offsetParent.offsetTop + dom.offsetHeight * i;
          if(!(items.length > 1 && i === items.length - 1 && item.ref.first)){
            item.ref.x = x;
            item.ref.y = y;
        }else{
          item.ref.x = -1;
          item.ref.y = -1;
          item.ref.first = false;
        }
        } else {
          item.ref.x = 0;
          item.ref.y = 0;
        }
      }
    }
  }

  /**
   * 强制更新组件
   *
   * @author chitanda
   * @date 2021-06-06 12:06:51
   * @return {*}  {Promise<void>}
   */
  @Method()
  async forceUpdate(): Promise<void> {
    const item = this.items.find(item => item.ref.getAttribute('show') == 'true');
    if (item) {
      this.overlayIndex = item.ref.overlayIndex;
      this.bodyOverflowDisable();
    } else {
      this.bodyOverflowEnable();
    }
    forceUpdate(this);
  }

  /**
   * 隐藏所有窗口
   *
   * @author chitanda
   * @date 2021-06-11 16:06:24
   * @return {*}  {Promise<void>}
   */
  @Method()
  async hiddenAll(): Promise<void> {
    this.items.forEach(self => {
      self.ref.hide();
    });
  }

  /**
   * body禁用滚动条
   *
   * @author chitanda
   * @date 2021-07-15 10:07:26
   */
  bodyOverflowDisable(): void {
    const html = document.lastElementChild as HTMLElement;
    html.style.overflow = 'hidden';
    document.body.style.overflow = 'hidden';
  }

  /**
   * body启用滚动条
   *
   * @author chitanda
   * @date 2021-07-15 10:07:35
   */
  bodyOverflowEnable(): void {
    const html = document.lastElementChild as HTMLElement;
    html.style.overflow = '';
    document.body.style.overflow = '';
  }

  render() {
    if (this.items && this.items.length === 0) {
      return null;
    }
    return (
      <Host
        id='ibz-drawer-exp'
        class={{ 'ibz-drawer-exp': true, 'not-active': this.hidden }}
        style={{ 'z-index': (this.overlayIndex + 1).toString(), display: this.items[0].ref.showExp ? 'block' : 'none' }}
      >
        <div ref={ref => (this.ref = ref)} class='ibz-drawer-actions'>
          {this.items
            ? this.items.map(item => {
                return (
                  <div
                    key={item.id}
                    class={{ 'ibz-drawer-exp-item': true, active: !item.ref.hidden }}
                    onClick={(e: MouseEvent) => this.showChange(e, item)}
                    title={item.ref.caption}
                  >
                    <div class='exp-item-label'>{item.ref.caption}</div>
                    <div
                      title='关闭窗口'
                      class='exp-item-close'
                      onClick={(e: MouseEvent) => {
                        e.stopPropagation();
                        item.ref.dismiss();
                      }}
                    >
                      <svg
                        class='icon'
                        viewBox='0 0 1024 1024'
                        version='1.1'
                        xmlns='http://www.w3.org/2000/svg'
                        width='12'
                        height='12'
                      >
                        <path d='M810.666667 273.493333L750.506667 213.333333 512 451.84 273.493333 213.333333 213.333333 273.493333 451.84 512 213.333333 750.506667 273.493333 810.666667 512 572.16 750.506667 810.666667 810.666667 750.506667 572.16 512z'></path>
                      </svg>
                    </div>
                  </div>
                );
              })
            : ''}
        </div>
        <div class='ibz-drawer-state' onClick={() => (this.hidden = !this.hidden)}>
          <div class='label'>收起</div>
          <div class='icon'>
            <svg
              class='icon'
              viewBox='0 0 1024 1024'
              version='1.1'
              xmlns='http://www.w3.org/2000/svg'
              width='12'
              height='12'
            >
              <path d='M320 928a36.48 36.48 0 0 1-17.92-5.12 32.64 32.64 0 0 1-8.96-44.8L537.6 512 293.12 145.92a32 32 0 0 1 53.76-35.84l256 384a33.28 33.28 0 0 1 0 35.84l-256 384a33.28 33.28 0 0 1-26.88 14.08z'></path>
              <path d='M576 928a36.48 36.48 0 0 1-17.92-5.12 32.64 32.64 0 0 1-8.96-44.8L793.6 512 549.12 145.92a32 32 0 1 1 53.76-35.84l256 384a33.28 33.28 0 0 1 0 35.84l-256 384a33.28 33.28 0 0 1-26.88 14.08z'></path>
            </svg>
          </div>
        </div>
      </Host>
    );
  }
}
